import expenseService from "../expense.service";
import { message, Modal } from "antd";
import { messages, queryCurrencyPrecision } from "share/common";
import React from "react";
import { openModal, removeContainer } from "components/method/openModal";
import ExpenseCheckResult from "containers/expense-report/components/expense-check-result";

const _showErrorMessage = (errorList, context) => {
  let container;
  let props = {
    visible: true,
    infoMessage: <p>{messages("expense-1.key47") /*请检查费用信息：*/}</p>,
    checkResult: errorList.map((i) => {
      i.type = 1;
      return i;
    }),
    cancelText: messages("expense-1.key48") /*返回修改*/,
    onCancel: () => close(),
    afterClose: () => {
      removeContainer(container);
      container = null;
    },
  };
  let close = () => {
    openModal(
      ExpenseCheckResult,
      { ...props, visible: false },
      context,
      container
    );
  };
  container = openModal(ExpenseCheckResult, props, context);
};

export function auditSaveReceipt(params, onSuccess, context) {
  return expenseService
    .saveAuditEditReceipt(params)
    .then((res) => {
      message.success(messages("common.operate.success") /*操作成功*/);
      return onSuccess && onSuccess(res);
    })
    .catch((err) => {
      if (!err.response || !err.response.data) {
        messages("common.operate.filed") /*操作失败*/;
        return false;
      }
      let error = err.response.data;
      if (
        error &&
        error.validationErrors &&
        error.validationErrors.length > 0
      ) {
        _showErrorMessage(error.validationErrors, context);
        return false;
      }
      if (error.message) {
        message.error(
          messages("expense-1.key47") /*请检查费用信息：*/ + error.message
        );
      }
      return false;
    });
}

export function shouldChangeFeeAutomatic({
  type,
  params,
  currentReceipt,
  validAuth,
  onConfirm,
  onDefaultConfirm,
  onCancel,
  renderModalContent,
}) {
  let title, content;
  let onConfirmChangeExpenseAmount = onDefaultConfirm;
  let showConfirmModal = false;

  let showDeleteConfirmModal = (resolve, reject) => {
    Modal.confirm({
      title: title || messages("expense-1.key49") /*确认删除*/,
      content:
        content ||
        (renderModalContent
          ? renderModalContent()
          : messages("expense-1.key50")) /*确认删除该发票？*/,
      okText: messages("expense-1.key51") /*确认*/,
      cancelText: messages("common.cancel") /*取消*/,
      onOk: () => (resolve ? resolve() : onConfirmChangeExpenseAmount()),
      onCancel: () => (reject ? reject() : onCancel ? onCancel() : null),
    });
  };
  //不同场景下操作发票，去校验是否核小费用金额的权限
  if (validAuth) {
    return expenseService
      .shouldAuditAmount(params)
      .then((res) => {
        let { amountAutoChange, originalAmount, amount } = res.data.rows;
        if (amountAutoChange) {
          let difference = (originalAmount - amount).toFixed(2);
          content = messages("expense-1.key52", {
            arg1: currentReceipt.vatInvoiceCurrencyCode,
            arg2: React.Component.prototype.filterMoney(
              originalAmount,
              queryCurrencyPrecision(currentReceipt.vatInvoiceCurrencyCode),
              true
            ),
            arg3: currentReceipt.vatInvoiceCurrencyCode,
            arg4: React.Component.prototype.filterMoney(
              amount,
              queryCurrencyPrecision(currentReceipt.vatInvoiceCurrencyCode),
              true
            ),
            arg5: difference,
          }) /*费用金额将从{arg1}{arg2}核定为{arg3}{arg4}。核定差额为{arg5}*/;
          if (type === "DELETE") {
            title = messages("expense-1.key49") /*确认删除*/;
          }
          if (type === "EDIT") {
            title = messages("expense-1.key53") /*确认修改*/;
          }
          if (type === "ADD") {
            title = messages("expense-1.key54") /*新增发票*/;
          }
          onConfirmChangeExpenseAmount = () => onConfirm(res.data.rows);
          showConfirmModal = true;
        }
        if (type === "DELETE" || showConfirmModal) {
          return new Promise((resolve, reject) => {
            showDeleteConfirmModal(resolve, reject);
          })
            .then(() => onConfirmChangeExpenseAmount())
            .catch(() => onCancel && onCancel());
        } else {
          return onDefaultConfirm && onDefaultConfirm();
        }
      })
      .catch((e) => {
        console.log(e);
      });
  } else {
    return type === "DELETE"
      ? showDeleteConfirmModal()
      : onDefaultConfirm && onDefaultConfirm();
  }
}
